<template>
	<div>
		{{ num }} =>{{ 'computed：' + numComputed }}
		<button @click="changeNUm(1)">加+</button>
		<button @click="changeNUm(-1)">减-</button>
	</div>
	<hr />
	<div>
		这是props内的数据：{{ testMsg }}
		<br />
		这是setup内的计算属性： {{ setComputed }}
		<br />
		<!-- {{ userInfo.name }} -->
		<!-- {{ userInfo.age }} -->
		<!-- {{ loginInfo }} -->
	</div>
	<button @click="testMsg = '这是改变后的testMsg'">改变testMsg</button>
	<hr />
	<p>{{ student.name }}</p>
	<p>{{ student.age }}</p>

	<hr />
	<p>第 {{ year }} 年</p>
	<p>姓名： {{ nickname }}</p>
	<p>年龄： {{ age }}</p>

	<hr />
	<p>{{ like }}</p>
	<button @click="changeUserInfo">点击改变</button>
</template>

<script lang="ts">
import { ref, toRefs, onMounted, onBeforeMount, reactive, defineComponent, toRef, readonly } from 'vue';
import numJS from './num';
import msgJS from './msg';
import { SetupContext } from '../../types/index';

interface Student {
	name: string;
	class?: string;
	age: number;
}
interface Data {
	[key: string]: unknown;
}

export default defineComponent({
	setup(props: Data, context: SetupContext) {
		console.log(context);

		console.log('props', props /* attrs, slots, emit */);

		/* 生命周期 */
		onBeforeMount(() => {
			console.log('%conBeforeMount', 'color:orange');
		});
		onMounted(function () {
			console.log('%conMounted', 'color:teal');
		});

		/* toRefs 解构回事响应式的，es6解构不会响应 */
		// const { msg } = toRefs<any>(props);

		/* toRef 创建一个 ref ，入参是响应式，返回结果才会响应，但是有其它ref响应更新时，结果就会响应*/
		// const userInfo = reactive({ sex: "boy", like: "girl" });
		const userInfo = { sex: 'boy', like: 'girl' };
		const like = toRef(userInfo, 'like');
		const changeUserInfo = () => {
			like.value = '20 girl';
			console.log(userInfo);
			console.log(like);
		};

		/* reactive响应数据 */
		// const student = reactive<Student>({ name: "阿勇", age: 16 });
		// or
		const student: Student = reactive({ name: '阿勇', age: 16 });
		// or
		// const student = reactive({
		//     name: "阿勇",
		//     age: 16,
		//     class: "cs",
		// }) as Student;

		// TODO  拷贝一份proxy对象将其设置为只读
		// readonly(student)

		/* 以下时将逻辑分别提取到各自文件了，逻辑分明 */
		const { num, changeNUm, numComputed } = numJS();
		// @ts-ignore
		const testMsg = ref('abcdefg');
		const { setComputed } = msgJS(testMsg);

		/* ref reactive */
		const year = ref(0);
		const user = reactive({ nickname: 'xiaofan', age: 26, gender: '女' });
		setInterval(() => {
			// year.value += 1;
			// user.age += 1;
		}, 1000);

		return {
			num,
			changeNUm,
			setComputed,
			numComputed,
			student,
			year,
			testMsg,
			like,
			changeUserInfo,
			...toRefs(user),
		};
	},
	beforeCreate() {
		console.log('beforeCreate');
	},
	created() {
		console.log('created');
	},
	mounted() {
		console.log('%cmounted', 'color:red');
	},
	unmounted() {
		console.log('unmounted');
	},
	renderTriggered(event) {
		console.log(event);
	},
	methods: {},
});
</script>
